function isNumber(num){
  return !isNaN(parseFloat(num)) && isFinite(num)
}

function addOneNumber(num){
  return Number(num) + Number(1)
}

function reduceOneNumber(num){
  return Number(num) - Number(1)
}

jQuery(function($){

  // start add to cart
  $("a#add_to_cart_items").on("click", function(e){
		e.preventDefault();
		var quantity = $("input#add_to_cart_items_quantity_in_show").val()
		var productId = $(this).data("id");
		var storeId = $(this).data("store-id");
    if(isNumber(quantity)){
      // is a number
      $.ajax({
  			url: "/api/store_customers/is_logged",
  			method: "get",
  			success: function(data){
  				if(data.status == true){
  					var csrf = $("input#js-sale-product-show").val();
  					$.ajax({
  						url: "/api/cart_items",
  						method: "post",
  						headers: {
                        'X-CSRF-Token': csrf
                      },
  						data: {store_id: storeId, store_product_id: productId, quantity: quantity},
  						success: function(data){
  							if(data.status == true){
  								location.href = "/sales/cart_items/"+ data.cart_item_id +"/successful?store_id="+ storeId
  							}else {
  								showErrorView(data.message);
  							}
  						}
  					})
  				}else {
  					showErrorView("请您先进行登录!");
  					return false;
  				}
  			}
  		})
    }else {
      console.log(quantity);
      console.log(isNumber(quantity));
      showErrorView("请输入正确的数字!");
      return false
    }
	});
  // end to add cart

  // 添加到购物车数量的控制
	$("a.js-add-to-cart-num").on("click", function(){
		var num = $("input#add_to_cart_items_quantity_in_show").val();
		if(isNumber(num)){ // true is number
			$("input#add_to_cart_items_quantity_in_show").val(Number(num) + Number(1));
			$("a.js-reduce-to-cart-num").removeClass("disabled");
		}else {
			$("input#add_to_cart_items_quantity_in_show").val(1);
			$("a.js-reduce-to-cart-num").addClass("disabled");
		}
	});

	$("a.js-reduce-to-cart-num").on("click", function(){
		var num = $("input#add_to_cart_items_quantity_in_show").val();
		if(isNumber(num)){ // true is number
			var currentNum = Number(num) - Number(1)
			if(currentNum < 1){
				$("input#add_to_cart_items_quantity_in_show").val(1);
				$("a.js-reduce-to-cart-num").addClass("disabled");
			}else {
				$("input#add_to_cart_items_quantity_in_show").val(currentNum);
				$("a.js-reduce-to-cart-num").removeClass("disabled");
			}
		}else {
			// is not a number
			$("input#add_to_cart_items_quantity_in_show").val(1);
			$("a.js-reduce-to-cart-num").addClass("disabled");
		}
	});


});
